/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React from 'react';
import { TreeSelect } from 'antd';
import { MenuDataItem } from '@ant-design/pro-layout';
import { useLocation, history } from 'umi';
import styles from './index.less';

const { TreeNode } = TreeSelect;

export interface HeaderSearchProps {
  menuData?: MenuDataItem[];
}

const HeaderSearch: React.FC<HeaderSearchProps> = (props) => {
  const { menuData } = props;
  const { pathname } = useLocation();

  const handleSelect = (value: any) => {
    const path = value.split('|').slice(-1)[0];
    if (!path || path === pathname) return;
    history.push(path);
  };

  return (
    <TreeSelect
      showSearch
      style={{ width: 240 }}
      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
      placeholder='请输入目标菜单'
      allowClear
      treeDefaultExpandAll
      onSelect={handleSelect}
      className={styles.search}
    >
      {menuData?.map((item) => {
        const { name = '', routes, key = '' } = item;
        const itemValue = `${name}|${key}`;
        return (
          <TreeNode value={itemValue} title={name} key={itemValue} selectable={false}>
            {routes?.map((childItem) => {
              const { name: childName = '', key: childKey = '' } = childItem;
              const childItemValue = `${childName}|${childKey}`;
              return <TreeNode value={childItemValue} title={childName} key={childItemValue} />;
            })}
          </TreeNode>
        );
      })}
    </TreeSelect>
  );
};

export default HeaderSearch;
